import { Button, Form, Input, Space, Tabs } from 'antd';
import { SupplierLocaldataContext } from '../common';
import { useContext, useMemo, useRef, useState } from 'react';
import pageStyles from '@/common/pageLayout.less';
import { DoubleLeftOutlined, DoubleRightOutlined, PlusOutlined, UpCircleOutlined, DownCircleOutlined, SearchOutlined, ReloadOutlined } from '@ant-design/icons';
import { UpdateViewLeftForm } from './UpdateViewLeftForm';
import { QualifyTabsPaneView } from './QualifyTabsPaneView';
import { QualifyUpdateModal } from './QualifyUpdateModal';
import { MemoirUpdateModal } from './MemoirUpdateModal';
import { MemoirRightTabsPane } from './MemoirRightTabsPane';
import { DetailViewLeftChangeInfo } from './DetailViewLeftChangeInfo';
import { onMouseOutBtn } from '@/utils';

export const UpdateViewLeft: React.FC = () => {
  /** 搜索表单 */
  const [searchForm] = Form.useForm();

  /** 获取上下文 */
  const { locationID, memoirDataList, curRes, supplierInfoObj, qualifyDataList } = useContext(SupplierLocaldataContext);

  /** 资质组件ref */
  const qualifyPaneRef: any = useRef();

  /** 负面影响组件ref */
  const memoirPaneRef: any = useRef();

  /** 展示资质添加弹框 */
  const [isQualifiModalObj, setIsQualifiModalObj] = useState<Record<string, any>>({
    showModal: false,
    checkRows: {},
  });

  /** 展示大事件弹框 */
  const [isMemoirModalObj, setIsMemoirModalObj] = useState<Record<string, any>>({
    showModal: false,
    checkRows: {},
  });

  /** 变更记录展开关闭 */
  const [chanageListOpen, setChangeListOpen] = useState<Record<string, any>>({
    allOpenKeys: [],
    openIdKey: [],
  });

  /** 大事件展开关闭 */
  const [memoirListOpen, setMemoirListOpen] = useState<Record<string, any>>({
    allOpenKeys: [],
    openIdKey: [],
  });

  /**保存当前选中Tabs 下标 */
  const [tabsInfoPaneKey, setTabsInfoPaneKey] = useState<string>('1');

  /** 切换Tabs页面保存 */
  const tabsInfoChanage = (activeKey: string) => {
    setTabsInfoPaneKey(activeKey);
  };

  /**  面板展开关闭 */
  const [collapseKey, setCollapseKey] = useState<string[] | any>(['InformationPanel', 'registrationPanel', 'contactsPanel']);

  /**
   * 折叠面板全选于反选
   * @param clickType 类型
   */
  const collAllRemove = (clickType: string) => {
    if (clickType == 'allOpen') {
      setCollapseKey(['InformationPanel', 'registrationPanel', 'contactsPanel']);
    } else if (clickType == 'allClose') {
      setCollapseKey([]);
    }
  };

  /** 点击折叠面板关闭展开 */
  const collapseChange = (selCollKey: string | string[]) => {
    setCollapseKey(selCollKey);
  };

  /** 判断资质描述和负面影响 */
  const qualifyMemoirBtn = useMemo(() => {
    let allBtn: Record<string, any> = {
      qualifyBtn: false,
      memoirBtn: false,
    };
    if (curRes?.['/supplierQualifyController/add']) {
      if (supplierInfoObj && supplierInfoObj?.id) {
        if (supplierInfoObj?.isBlack == 0 && !supplierInfoObj?.cancelerID) {
          allBtn['qualifyBtn'] = true;
        }
      } else {
        allBtn['qualifyBtn'] = true;
      }
    }

    if (curRes?.['/supplierMemoirController/add']) {
      if (supplierInfoObj && supplierInfoObj?.id) {
        if (supplierInfoObj?.isBlack == 0 && !supplierInfoObj?.cancelerID) {
          allBtn['memoirBtn'] = true;
        }
      } else {
        allBtn['memoirBtn'] = true;
      }
    }
    return allBtn;
  }, [curRes, supplierInfoObj]);

  /**
   * 点击单个数据展开关闭
   * @param clickKey 点击的数据ID
   */
  const clickOpenClose = (clickKey: string, allOpenChildren: Record<string, any>) => {
    if (allOpenChildren?.openIdKey?.includes(clickKey)) {
      const closeDataKeys: string[] = allOpenChildren?.openIdKey?.filter((item: any) => item != clickKey);
      const newOpenKeys: Record<string, any> = {
        ...allOpenChildren,
        openIdKey: closeDataKeys,
      };
      if (tabsInfoPaneKey == '4') {
        setChangeListOpen(newOpenKeys);
      } else if (tabsInfoPaneKey == '3') {
        setMemoirListOpen(newOpenKeys);
      }
    } else {
      const openDataKeys: string[] = [...allOpenChildren?.openIdKey];
      openDataKeys?.push(clickKey);
      const newOpenKeys: Record<string, any> = {
        ...allOpenChildren,
        openIdKey: openDataKeys,
      };
      if (tabsInfoPaneKey == '4') {
        setChangeListOpen(newOpenKeys);
      } else if (tabsInfoPaneKey == '3') {
        setMemoirListOpen(newOpenKeys);
      }
    }
  };

  /**
   * 展开收起全部按钮dom
   * @param listOpen 保存的state
   * @param changeOpenSetState 修改state的方法
   * @returns
   */
  const openCloseBtn = (listOpen: Record<string, any>, changeOpenSetState: (obj: Record<string, any>) => void) => {
    return (
      <Button
        className="manageBtntTxtStyle"
        type="link"
        icon={listOpen?.openIdKey?.length > 0 ? <UpCircleOutlined /> : <DownCircleOutlined />}
        size="small"
        onClick={() => {
          if (listOpen?.openIdKey?.length > 0) {
            changeOpenSetState({
              ...listOpen,
              openIdKey: [],
            });
          } else {
            const openList: string[] = [...listOpen?.allOpenKeys];
            changeOpenSetState({
              ...listOpen,
              openIdKey: openList,
            });
          }
        }}
        onMouseOut={onMouseOutBtn}
      >
        {listOpen?.openIdKey?.length > 0 ? '收起全部' : '展开全部'}
      </Button>
    );
  };

  /**
   * 点击搜索
   * @param searchType   true:资质  false:不良影响
   */
  const searchQualifyAndMemoir = (searchType: boolean) => {
    const searchParams: Record<string, any> = searchForm?.getFieldsValue();
    if (searchType) {
      const qualifySearch: Record<string, any> = {
        attachContent: searchParams?.attachContent,
      };
      qualifyPaneRef?.current?.searchQualify(qualifySearch);
    } else {
      const memoirSearch: Record<string, any> = {
        memoirResult: searchParams?.memoirResult,
        memoirInfo: searchParams?.memoirResult,
      };
      memoirPaneRef?.current?.searchMemoir(memoirSearch);
    }
  };

  /**
   * 刷新资质和负面影响
   * @param reloadType  true:资质  false :负面
   */
  const reloadSearchTabsPane = (reloadType: boolean) => {
    searchForm?.resetFields();
    if (reloadType) {
      qualifyPaneRef?.current?.reloadQualify({});
    } else {
      memoirPaneRef?.current?.reloadMemoir({});
    }
  };

  /** tabs页面右侧操作按钮 */
  const contactsTabsExtra = useMemo(() => {
    if (tabsInfoPaneKey == '1') {
      return (
        <Space>
          <Button
            type={collapseKey?.length == 0 ? 'dashed' : 'primary'}
            size={'small'}
            icon={<DoubleLeftOutlined className={'conmpanyCardExtra'} />}
            className="manageBtntTxtStyle"
            onClick={() => {
              collAllRemove('allClose');
            }}
            disabled={collapseKey?.length == 0 ? true : false}
          >
            全部折叠
          </Button>
          <Button
            type={collapseKey?.length != 0 ? 'dashed' : 'primary'}
            size={'small'}
            icon={<DoubleRightOutlined className={'conmpanyCardExtra'} />}
            className="manageBtntTxtStyle"
            onClick={() => {
              collAllRemove('allOpen');
            }}
            disabled={collapseKey?.length == 2 ? true : false}
          >
            全部展开
          </Button>
        </Space>
      );
    } else if (tabsInfoPaneKey == '2') {
      // if (supplierInfoObj?.isBlack == '0' && !supplierInfoObj?.cancelerID)
      return (
        <Space>
          {qualifyDataList && qualifyDataList?.length > 0 && (
            <Form.Item name="attachContent" style={{ marginBottom: 0 }}>
              <Input
                placeholder="按资质描述查询"
                style={{ borderRadius: 50, width: 250 }}
                suffix={
                  <Space>
                    <a
                      onClick={() => {
                        searchQualifyAndMemoir(true);
                      }}
                    >
                      <SearchOutlined />
                    </a>
                    <a
                      onClick={() => {
                        reloadSearchTabsPane(true);
                      }}
                    >
                      <ReloadOutlined />
                    </a>
                  </Space>
                }
              />
            </Form.Item>
          )}
          {qualifyMemoirBtn?.qualifyBtn && (
            <Button
              type={'link'}
              size="small"
              onMouseOut={onMouseOutBtn}
              // icon={<PlusOutlined />}
              onClick={() => {
                setIsQualifiModalObj({
                  showModal: true,
                  checkRows: {},
                });
              }}
              className="manageBtntTxtStyle"
            >
              添加
            </Button>
          )}
        </Space>
      );
    } else if (tabsInfoPaneKey == '3') {
      return (
        <Space>
          {memoirDataList && memoirDataList?.length > 0 && (
            <Form.Item name="memoirResult" style={{ marginBottom: 0 }}>
              <Input
                placeholder="按事件结果或事件描述查询"
                style={{ borderRadius: 50, width: 250 }}
                suffix={
                  <Space>
                    <a
                      onClick={() => {
                        searchQualifyAndMemoir(false);
                      }}
                    >
                      <SearchOutlined />
                    </a>
                    <a
                      onClick={() => {
                        reloadSearchTabsPane(false);
                      }}
                    >
                      <ReloadOutlined />
                    </a>
                  </Space>
                }
              />
            </Form.Item>
          )}
          {qualifyMemoirBtn?.memoirBtn && (
            <Button
              size="small"
              onMouseOut={onMouseOutBtn}
              // icon={<PlusOutlined />}
              onClick={() => {
                setIsMemoirModalObj({
                  showModal: true,
                  checkRows: {},
                });
              }}
              type={'link'}
              className="manageBtntTxtStyle"
            >
              添加
            </Button>
          )}
          {memoirDataList?.length > 0 ? openCloseBtn(memoirListOpen, setMemoirListOpen) : <></>}
        </Space>
      );
    } else if (tabsInfoPaneKey == '4') {
      return openCloseBtn(chanageListOpen, setChangeListOpen);
    }
  }, [tabsInfoPaneKey, collapseKey, chanageListOpen, memoirListOpen, memoirDataList, qualifyDataList]);

  const tabPaneItems = useMemo(() => {
    const tabItems = [
      {
        label: '供应商信息',
        key: '1',
        children: <UpdateViewLeftForm supplierCollapseKey={collapseKey} collapseChange={collapseChange} />,
      },
      // {
      //   label: '相关资质',
      //   key: '2',
      //   children: <QualifyTabsPaneView ref={qualifyPaneRef} openIsQualifiModal={setIsQualifiModalObj} />,
      // },
      // {
      //   label: '负面影响',
      //   key: '3',
      //   children: (
      //     <MemoirRightTabsPane
      //       ref={memoirPaneRef}
      //       allOpenChildren={memoirListOpen}
      //       changeOpenChildren={setMemoirListOpen}
      //       clickOpenClose={clickOpenClose}
      //       showUpdateMemoirModal={setIsMemoirModalObj}
      //     />
      //   ),
      // },
    ];

    // if (locationID) {
    //   tabItems?.push({
    //     label: '变更记录',
    //     key: '4',
    //     children: <DetailViewLeftChangeInfo allOpenChildren={chanageListOpen} changeOpenChildren={setChangeListOpen} clickOpenClose={clickOpenClose} />,
    //   });
    // }

    return tabItems;
  }, [locationID, tabsInfoPaneKey, collapseKey, chanageListOpen, memoirListOpen, memoirDataList]);

  return (
    <>
      <Tabs
        activeKey={tabsInfoPaneKey}
        className={pageStyles['commonTabs']}
        type="card"
        onChange={tabsInfoChanage}
        destroyInactiveTabPane={false}
        // tabBarExtraContent={<Form form={searchForm}>{contactsTabsExtra}</Form>}
        items={tabPaneItems}
      />

      {/* 资质信息弹框 */}
      {isQualifiModalObj?.showModal && (
        <QualifyUpdateModal
          onClose={() => {
            setIsQualifiModalObj({
              showModal: false,
              checkRows: {},
            });
          }}
          qualifiCheckRows={isQualifiModalObj?.checkRows}
          reloadQualifyManage={qualifyPaneRef?.current?.refreshQualifyPane}
        />
      )}

      {/* 大事件弹框 */}
      {isMemoirModalObj?.showModal && (
        <MemoirUpdateModal
          onClose={() => {
            setIsMemoirModalObj({
              showModal: false,
              checkRows: {},
            });
          }}
          memoirCheckRows={isMemoirModalObj?.checkRows}
          reloadMemoirManage={memoirPaneRef?.current?.refreshMemoirPane}
        />
      )}
    </>
  );
};
